package com.esheeper.staticserver.interceptor;

import com.esheeper.staticserver.Util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.file.FileSystems;
import java.nio.file.Path;

@Configuration//定义此类为配置类
public class InterceptorConfig implements WebMvcConfigurer {
    @Autowired
    AuthorizationInterceptor authorizationInterceptor;
    @Value("${file.store-dir:assets/}")
    private String dir;

    @Value("${file.serve-path:assets/**}")
    private String servePath;

    /**
     * 跨域设置
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }

    /**
     * 拦截处理请求信息
     * 添加文件真实地址
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(getDirServePath())
                .addResourceLocations("file:" + getAbsDir() + "/");
    }

    /**
     * 获取服务器url
     * @return
     */
    private String getDirServePath() {
        return servePath;
    }

    /**
     * 获得文件夹的绝对路径
     */
    private String getAbsDir() {
        if (FileUtil.isAbsolutePath(dir)) {
            return dir;
        }
        String cmd = System.getProperty("user.dir");
        Path path = FileSystems.getDefault().getPath(cmd, dir);
        return path.toAbsolutePath().toString();
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //addPathPatterns拦截的路径
        String[] addPathPatterns = {
                "/**"
        };
        // 排除拦截路径
        //        excludePathPatterns排除的路径
        //        String[] excludePathPatterns = {
        //                "/user/login", "/user/noLg", "/user/error"
        //        };
        //创建用户拦截器对象并指定其拦截的路径和排除的路径
        registry.addInterceptor(authorizationInterceptor).addPathPatterns(addPathPatterns);

        // 添加排除拦截路径
        //.excludePathPatterns(excludePathPatterns);
    }
}